package com.example.basic.utils;

import io.swagger.annotations.ApiModelProperty;

import java.lang.reflect.Field;
import java.util.*;


public class ObjectUtils {

    /**
     * 将对象转换成map.
     * @param object
     * @return
     */
    public static Map<String, Object> toMap(Object object){
        if(object == null){
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] declaredFields = object.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            boolean annotationPresent = field.isAnnotationPresent(ApiModelProperty.class);
            if (!annotationPresent) {
                continue;
            }
            field.setAccessible(true);
            try {
                if("java.util.Date".equals(field.getType().getName()) && field.get(object)!=null){
                    map.put(field.getName(), DateUtils.format((Date) field.get(object), "yyyy-MM-dd HH:mm:ss"));
                }else{
                    map.put(field.getName(), field.get(object));
                }

            } catch (IllegalAccessException e){

            } finally {

            }
        }
        return map;
    }

    /**
     * splitAry方法<br>
     * @param ary 要分割的数组
     * @param subsize 分割的块大小
     * @return
     *
     */
    public static Object[] splitAry(byte[] ary, int subsize) {
        int count = ary.length % subsize == 0 ? ary.length / subsize: ary.length / subsize + 1;
        List<List<Byte>> subAryList = new ArrayList<List<Byte>>();
        for (int i = 0; i < count; i++) {
            int index = i * subsize;
            List<Byte> list = new ArrayList<Byte>();
            int j = 0;
            while (j < subsize && index < ary.length) {
                list.add(ary[index++]);
                j++;
            }
            subAryList.add(list);
        }

        Object[] subAry = new Object[subAryList.size()];
        for(int i = 0; i < subAryList.size(); i++){
            List<Byte> subList = subAryList.get(i);
            byte[] subAryItem = new byte[subList.size()];
            for(int j = 0; j < subList.size(); j++){
                subAryItem[j] = subList.get(j);
            }
            subAry[i] = subAryItem;
        }
        return subAry;
    }

    /**
     * 利用HashSet剔除list的重复元素
     * @param list
     * @return
     */
    public static List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }
}
